var rootScope = null;
var Groups = {
  '*': {
    text: '所有',
    type: '*'
  }
};
var app = angular.module('myApp', ['treeControl']);

function baseController ($scope, $http, ajaxURL, pageNowName) {
  rootScope = $scope;
  rootScope.Groups = Groups;
  $scope.grounpSelectInput = '所有'
  $scope.searchGroupTreeInput = ''
  $scope.searchAddGroupTreeInput = ''
  $scope.pages = {
    data: [],
    count: 0,
    maxPage: "...",
    pageNow: 1,
  };
  $scope.status_str = [{
    css: 'danger',
    label: '卸载'
  }, {
    css: 'success',
    label: '在线'
  }, {
    css: 'warning',
    label: '断线'
  }];

  /*
   * 0：卸载
   * 1：在线
   * 2：断线
   * */

  //卸载数组
  $scope.sensorDangerList = [];

  //在线数组
  $scope.sensorsuccessList = [];

  //下拉框条数
  $scope.select_model = [{
    num: '10',
    type: "10条/页"
  },
  {
    num: '20',
    type: "20条/页"
  },
  {
    num: '50',
    type: "50条/页"
  },
  {
    num: '100',
    type: "100条/页"
  },
  ];
  $scope.select = {
    model: '10'
  }

  $scope.isolate_str = ['text-blue', 'text-gray'];
  $scope.pause_str = ['glyphicon-play text-green', 'glyphicon-pause text-yellow'];
  $scope.work_str = ['', 'glyphicon-hourglass text-yellow', 'glyphicon-ok text-green', 'glyphicon-remove text-red'];
  $scope.scan_str = ['text-gray', 'text-blue'];
  $scope.SensorIDList = [];
  $scope.SensorList = {};
  $scope.WhiteList = {};

  $scope.searchType = "";
  $scope.postType = "";
  $scope.rsqType = "";
  $scope.postData = {};

  if (localStorage.getItem("sensorSearch")) {
    $scope.searchData = JSON.parse(localStorage.getItem("sensorSearch"))
    $scope.grounpSelectInput = JSON.parse(localStorage.getItem("grounpSelectInput"))
    console.log($scope.searchData);
    $scope.postData = angular.copy($scope.searchData);
  } else {
    $scope.searchData = {
      ComputerName: '*',
      ProfileVersion: '*',
      group: '*',
      SensorVersion: '*',
      status: '*',
      IP: '',
      SoftwareName: '',
      software: '',
      Hardware: '',
      OSType: '',
      updated_at: '*',
    };
    $scope.postData = angular.copy($scope.searchData);
  }
  $scope.setPage = function (rsp) {
    if (rsp.data.status != "success") {
      return;
    }
    $scope.pages = rsp.data;
    // console.log($scope.pages);
    angular.forEach($scope.pages.data, function (item) {
      item.hardwareShort = ''
      item.Softwareshort = ''
      if (item.hardware && item.hardware.HardwareInfoList.length != 0) {
        item.hardwareShort = item.hardware.HardwareInfoList[0].HardwareName + ':' + item.hardware.HardwareInfoList[0].HardwareInfo.substring(0, 7) + '...'
      }
      if (!Array.isArray(item.data)) {
        if (item.data && item.data.SoftwareInfoList && item.data.SoftwareInfoList.length != 0) {
          item.Softwareshort = item.data.SoftwareInfoList[0].DisplayName + ':' + item.data.SoftwareInfoList[0].DisplayVersion;
          item.Softwareshort = item.Softwareshort.substring(0, 10) + '...'
        }
      }
    });
    var ID4NewPage = [];
    for (var i in $scope.pages.data) {
      var sensor = $scope.pages.data[i];
      $scope.SensorList[sensor.SensorID] = sensor;
      ID4NewPage.push(sensor.SensorID);
    }
    for (var i = $scope.SensorIDList.length - 1; i >= 0; i--) {
      var SensorID = $scope.SensorIDList[i]
      if (ID4NewPage.indexOf(SensorID) == -1) {
        $scope.SensorIDList.splice(i, 1);
      }
    }
    if ($scope.postType) {
      $scope.rsqType = $scope.postType;
    }
    console.log(111111);
    console.log(pageNowName);

    sessionStorage.setItem(pageNowName, $scope.pages.pageNow);
  }
  $scope.getPage = function (pageNow) {
    pageNow = pageNow ? pageNow : sessionStorage.getItem(pageNowName);
    $scope.pageGeting = true;
    var postData = {};
    if ($scope.postData) {
      postData = angular.copy($scope.postData);
    }

    for (var key in postData) {
      if (postData[key] == '') {
        postData[key] = '*';
      }
    }

    console.log(888888);
    postData['page'] = pageNow;
    postData['rows'] = $scope.select.model;
    console.log(postData);

    $http.post(ajaxURL.getPage, postData).then(function success (rsp) {

      $scope.pageGeting = false;
      $scope.setPage(rsp);

    }, function err (rsp) {
      $scope.pageGeting = false;
    });
  }




  $scope.selectAll = function () {
    if ($scope.SensorIDList.length == $scope.pages.data.length) {
      $scope.SensorIDList = [];
      $scope.sensorsuccessList = [];
      $scope.sensorDangerList = [];
    } else {
      $scope.SensorIDList = [];
      $scope.sensorsuccessList = [];
      $scope.sensorDangerList = [];

      for (var i in $scope.pages.data) {
        var sensor = $scope.pages.data[i];
        $scope.SensorIDList.push(sensor.SensorID);
        ///
        let status = sensor.status;
        if (status == 0) {
          $scope.sensorDangerList.push(sensor.SensorID);
        } else if (status == 1) {
          $scope.sensorsuccessList.push(sensor.SensorID);
        }
      }
    }
  }

  $scope.selectOne = function (sensor, $event) {
    $event.stopPropagation();
    var index = $scope.SensorIDList.indexOf(sensor.SensorID);
    if (index == -1) {
      $scope.SensorIDList.push(sensor.SensorID);
    } else {
      $scope.SensorIDList.splice(index, 1);
    }
    ///
    let status = sensor.status;

    if (status == 0) {
      let idx = $scope.sensorDangerList.indexOf(sensor.SensorID);
      if (idx == -1) {
        $scope.sensorDangerList.push(sensor.SensorID);
      } else {
        $scope.sensorDangerList.splice(idx, 1);
      }

    } else if (status == 1) {
      let idx = $scope.sensorsuccessList.indexOf(sensor.SensorID);
      console.log(idx);
      if (idx == -1) {
        $scope.sensorsuccessList.push(sensor.SensorID);
      } else {
        $scope.sensorsuccessList.splice(idx, 1);
      }
    }
  }

  $scope.detail = function (SensorID) {
    // var Sensor = $scope.SensorList[SensorID];

    // var W = $(".content").width();
    // var H = (W/16)*9;
    // zeroModal.show({
    //     title: Sensor.ComputerName,
    //     content: "<pre>"+JSON.stringify(Sensor, null, 2)+"</pre>",
    //     width: W+"px",
    //     height: H+"px",
    //     cancel: true,
    //     overlayClose: true,
    //     onCleanup: function() {
    //     }
    // });
    location.href = "detail?sid=" + SensorID;
  }
  $scope.config = {
    ComputerName: true,
    status: true,
    IP: true,
    MacAddresses: false,
    OSType: false,
    group: false,
    SensorVersion: false,
    hardware: false,
    software: false,
    updated_at: false,
    created_at: false,
  }
  $scope.configCopy = {
    ComputerName: true,
    status: true,
    IP: true,
    MacAddresses: false,
    OSType: false,
    group: false,
    SensorVersion: false,
    hardware: false,
    software: false,
    updated_at: false,
    created_at: false,
  }
  $scope.getfieldList = function () {
    $scope.config = {
      ComputerName: true,
      status: true,
      IP: true,
      MacAddresses: false,
      OSType: false,
      group: false,
      SensorVersion: false,
      hardware: false,
      software: false,
      updated_at: false,
      created_at: false,
    }
    $http.get("/sensor/field-list").then(function success (rsp) {
      console.log(rsp.data.config);
      rsp.data.config.forEach(item => {
        for (var k in $scope.config) {
          if (k == item) {
            $scope.config[k] = true
          }
        }
      });
      $scope.configCopy = JSON.parse(JSON.stringify($scope.config))
    }, function err (rsp) {
    });
  }
  $scope.getfieldList()

  $scope.showConfigColumn = function () {
    $scope.getfieldList()
    var W = 300;
    var H = 480;
    zeroModal.show({
      title: '配置列',
      content: configColumn,
      width: W + "px",
      height: H + "px",
      ok: true,
      cancel: true,
      okFn: function () {
        console.log($scope.config);
        let reqData = {
          fields: []
        }
        for (var k in $scope.config) {
          if ($scope.config[k]) {
            reqData.fields.push(k)
          }
        }
        $http.put("/sensor/field-edit", reqData).then(function success (rsp) {
          console.log(rsp);
          if (rsp.data.status == 'success') {
            zeroModal.success({
              content: '修改配置成功'
            });

          }
          $scope.getfieldList()
        }, function err (rsp) {
        });

      },
      onCleanup: function () {
        hide_box.appendChild(configColumn);
      }
    });
  }

  function SensorIDValidate (callback) {
    var haveWorking = false;
    for (var i = $scope.SensorIDList.length - 1; i >= 0; i--) {
      var SensorID = $scope.SensorIDList[i];
      if ($scope.SensorList[SensorID].work == 1 || $scope.SensorList[SensorID].status != 1) {
        haveWorking = true;
        $scope.SensorIDList.splice(i, 1);
      }
    }
    if ($scope.SensorIDList.length == 0) {
      zeroModal.error({
        content: '操作失败',
        contentDetail: '请选择计算机！'
      });
      return;
    }

    if (haveWorking) {
      zeroModal.confirm({
        content: '操作提示',
        contentDetail: '当前正在执行命令的计算机无法执行此命令，<br>是否忽略这些计算机继续执行？',
        okFn: function () {
          callback();
        },
        cancelFn: function () { }
      });
    } else {
      callback();
    }
  }

  function setWorking () {
    for (var i = $scope.SensorIDList.length - 1; i >= 0; i--) {
      var Sensor = $scope.SensorList[$scope.SensorIDList[i]].work = 1;
    }
  }

  $scope.sendBase = function (type) {
    var W = 480;
    var H = 360;
    zeroModal.confirm({
      content: '确定要卸载吗？',
      width: W + "px",
      height: H + "px",
      okFn: function () {
        $scope.unSensor(type)
      },
      cancelFn: function () { }
    });
  }
  $scope.unSensor = function (type) {
    var rqs_data = {
      type: type,
      SensorIDList: $scope.sensorsuccessList
    };
    var loading = zeroModal.loading(4);
    $http.post("sendbase", rqs_data).then(function success (rsp) {
      setWorking();
      zeroModal.close(loading);
      $scope.sensorsuccessList = [];
      $scope.SensorIDList = [];
    }, function err (rsp) {
      zeroModal.close(loading);
    });
  }

  $scope.sendUpdate = function () {
    SensorIDValidate(function () {
      var W = 480;
      var H = 360;
      zeroModal.show({
        title: '请选择探针文件！',
        content: update_list,
        width: W + "px",
        height: H + "px",
        ok: true,
        cancel: true,
        okFn: function () {
          if (!updateNode) {
            zeroModal.error('请选择探针文件！');
            return false;
          }
          rqs_data = {
            type: 'UPDATE',
            SensorFile: updateNode,
            SensorIDList: $scope.sensorsuccessList
          };
          var loading = zeroModal.loading(4);
          $http.post("sendbase", rqs_data).then(function success (rsp) {
            setWorking();
            zeroModal.close(loading);

            $scope.sensorsuccessList = [];
            $scope.SensorIDList = [];

          }, function err (rsp) {
            zeroModal.close(loading);
          });
        },
        onCleanup: function () {
          hide_box.appendChild(update_list);
        }
      });
    });
  }

  $scope.sendUpdateProfile = function () {

    SensorIDValidate(function () {
      var W = 480;
      var H = 360;

      zeroModal.show({
        title: '请选择配置文件！',
        content: profile_list,
        width: W + "px",
        height: H + "px",
        ok: true,
        cancel: true,
        okFn: function () {
          if (!updateProfile) {
            zeroModal.error('请选择配置文件！');
            return false;
          }
          rqs_data = {
            type: 'UPDATE_PROFILE',
            ProFile: updateProfile,
            SensorIDList: $scope.sensorsuccessList
          };

          var loading = zeroModal.loading(4);
          $http.post("sendbase", rqs_data).then(function success (rsp) {
            setWorking();
            zeroModal.close(loading);

            $scope.sensorsuccessList = [];
            $scope.SensorIDList = [];

          }, function err (rsp) {
            zeroModal.close(loading);
          });
        },
        onCleanup: function () {
          hide_box.appendChild(profile_list);
        }
      });
    });
  }
  $scope.showSelected = function (node, selected) {
    console.log(9999);
    console.log(node);
    console.log(selected);
    $scope.grounpSelect = node
  }
  $scope.showAddSelected = function (node, selected) {
    console.log(9999);
    console.log(node);
    console.log(selected);
    $scope.grounpAddSelect = node
  }


  $scope.searchGroups = function () {
    $scope.getGroupTree()
    // $scope.oldDataForTheTree = arr
    // $scope.dataForTheTree = arr
    $scope.searchGroupTreeInput = ''
    var W = 480;
    var H = 360;
    $scope.option = 'hide';
    // $scope.$apply();
    zeroModal.show({
      title: '请选择计算机分组！',
      content: groupTree,
      width: W + "px",
      height: H + "px",
      ok: true,
      cancel: true,
      okFn: function () {
        console.log(111);
        console.log($scope.grounpSelect.text);
        $scope.$apply(function (params) {
          $scope.grounpSelectInput = $scope.grounpSelect.text
          localStorage.setItem("grounpSelectInput", JSON.stringify($scope.grounpSelectInput));
        })
        if ($scope.grounpSelect.id == 0) {
          $scope.searchData.group = '*';
        } else {
          $scope.searchData.group = $scope.grounpSelect.id
        }
      },
      onCleanup: function () {
        hide_box.appendChild(groupTree);
        $scope.option = 'show';
      }
    });
  }

  $scope.addGroups = function () {
    $scope.getAddGroupTree()
    var W = 480;
    var H = 360;
    zeroModal.show({
      title: '请选择计算机分组！',
      content: addgroupTree,
      width: W + "px",
      height: H + "px",
      ok: true,
      cancel: true,
      okFn: function () {
        console.log($scope.grounpAddSelect);

        if ($scope.grounpAddSelect.id == 0) {
          zeroModal.error('请选择计算机分组！');
          return false;
        }
        if ($scope.grounpAddSelect.type == 1) {
          zeroModal.error('不能加入自动分组！');
          return false;
        }
        var sidList = [];
        for (var i = $scope.sensorsuccessList.length - 1; i >= 0; i--) {
          var SensorID = $scope.sensorsuccessList[i];
          var sensor = $scope.SensorList[SensorID];
          sidList.push(sensor.id);
        }
        rqs_data = {
          gid: $scope.grounpAddSelect.id,
          sidList: sidList
        };
        var loading = zeroModal.loading(4);
        console.log(rqs_data);
        $http.post("addgroups", rqs_data).then(function success (rsp) {
          if (rsp.data.status == 'success') {
            zeroModal.success({
              content: '完成',
              contentDetail: '成功加入' + rsp.data.success + '台计算机！<br/>' + rsp.data.fail + '台计算机已经在此分组中。',
            });
          } else {
            zeroModal.error('加入计算机分组失败！');
          }
          zeroModal.close(loading);

          $scope.sensorsuccessList = [];
          $scope.SensorIDList = [];

        }, function err (rsp) {
          zeroModal.error('加入计算机分组失败！');
          zeroModal.close(loading);
        });
      },
      onCleanup: function () {
        hide_box.appendChild(addgroupTree);
      }
    });
  }

  //删除Sensor
  $scope.sendDelete = function () {
    var W = 480;
    var H = 360;

    zeroModal.confirm({
      content: '确定要删除吗？',
      width: W + "px",
      height: H + "px",
      okFn: function () {
        var rqs_data = {
          sid: $scope.sensorDangerList
        };
        var loading = zeroModal.loading(4);

        $http.delete("/sensor/del-sensor", {
          data: rqs_data
        })
          .then(function success (rsp) {
            //$scope.$apply();
            $scope.getPage();
            zeroModal.close(loading);

            $scope.sensorDangerList = [];
            $scope.SensorIDList = [];

          }, function err (rsp) {
            zeroModal.close(loading);
            zeroModal.error('删除计算机失败！');
          });
      },
      cancelFn: function () { }
    });
  }

  $scope.myKeyup = function (e) {
    var keycode = window.event ? e.keyCode : e.which;
    if (keycode == 13) {
      e.target.blur();
      $scope.search();
    }
  };

  $scope.getPage();

  //计算机列表分页点击事件
  $scope.getPageClick = function (pageNow) {
    $scope.SensorIDList = [];
    $scope.sensorsuccessList = [];
    $scope.sensorDangerList = [];
    $scope.getPage(pageNow);
  }

  // $scope.pageGeting = false;

  setInterval(function () {
    // if (!$scope.pageGeting) {
    $scope.getPage();
    // }
  }, 5000);


  // 选择页面数据条数,更新数据
  $scope.select_change = function () {
    $scope.getPage();
  }

  $scope.ShowDetail = function (content, type) {
    switch (type) {
      case 'hardware':
        $scope.HardwareInfoList = content.HardwareInfoList
        $scope.showHardwareInfo()
        break;
      case 'software':
        $scope.softwareInfoList = content.SoftwareInfoList
        $scope.showsoftwareInfo()
        break;
      default:
        break;
    }

  }
  $scope.showHardwareInfo = function () {
    var W = $(".content").width() * 0.8;
    var H = (W / 16) * 9;
    zeroModal.show({
      title: '硬件信息',
      content: showHardwareInfo,
      width: W + "px",
      height: H + "px",
      cancel: true,
      onCleanup: function () {
        hide_box.appendChild(showHardwareInfo);
      }
    });
  }
  $scope.showsoftwareInfo = function () {
    var W = $(".content").width() * 0.8;
    var H = (W / 16) * 9;
    zeroModal.show({
      title: '软件信息',
      content: showsoftwareInfo,
      width: W + "px",
      height: H + "px",
      cancel: true,
      onCleanup: function () {
        hide_box.appendChild(showsoftwareInfo);
      }
    });
  }


}

app.controller('protectCtrl', function ($scope, $http, $filter) {
  console.log(999999);
  $scope.getGroupTree = function () {
    $http.get('/group/tree').then(function success (rsp) {
      let arr = [
        {
          id: 0,
          text: '所有',
          child: rsp.data.data
        }
      ]
      $scope.oldDataForTheTree = arr
      $scope.dataForTheTree = arr
    }, function err (rsp) {
    });
  }
  $scope.getAddGroupTree = function () {
    $http.get('/group/tree').then(function success (rsp) {
      let arr = [
        {
          id: 0,
          text: '所有',
          child: rsp.data.data
        }
      ]
      $scope.oldAddDataForTheTree = arr
      $scope.dataAddForTheTree = arr
    }, function err (rsp) {
    });
  }
  $scope.getGroupTree()
  $scope.getAddGroupTree()
  $scope.searchGroupTree = function () {
    let newdataForTheTree = JSON.parse(JSON.stringify($scope.oldDataForTheTree))
    let arr = []
    $scope.treeTArr(newdataForTheTree).map(function (item) {
      console.log(item);
      console.log(item.text.search($scope.searchGroupTreeInput));
      if (item.text.search($scope.searchGroupTreeInput) != -1) {
        arr.push(item)
      }
    })
    console.log(arr);
    $scope.dataForTheTree = $scope.ArrToTree(arr)
  }
  $scope.searchAddGroupTree = function () {
    let newdataForTheTree = JSON.parse(JSON.stringify($scope.oldAddDataForTheTree))
    let arr = []
    $scope.treeTArr(newdataForTheTree).map(function (item) {
      console.log(item);
      console.log(item.text.search($scope.searchAddGroupTreeInput));
      if (item.text.search($scope.searchAddGroupTreeInput) != -1) {
        arr.push(item)
      }
    })
    console.log(arr);
    $scope.dataAddForTheTree = $scope.ArrToTree(arr)
  }
  $scope.dataForTheTree = [];
  $scope.dataAddForTheTree = [];


  baseController($scope, $http, {
    getPage: "protect",
    update: "update"
  }, "protectNow");

  // 树形结构数据转单层数组形式
  $scope.treeTArr = function (nodes) {
    var r = [];
    if (Array.isArray(nodes)) {
      for (var i = 0, l = nodes.length; i < l; i++) {
        r.push(nodes[i]); // 取每项数据放入一个新数组
        if (Array.isArray(nodes[i]["child"]) && nodes[i]["child"].length > 0)
          // 若存在children则递归调用，把数据拼接到新数组中，并且删除该children
          r = r.concat($scope.treeTArr(nodes[i]["child"]));
        delete nodes[i]["child"]
      }
    }
    return r;

  }

  $scope.ArrToTree = function (treeArray) {
    var r = [];
    var tmpMap = {};
    for (var i = 0, l = treeArray.length; i < l; i++) {
      // 以每条数据的id作为obj的key值，数据作为value值存入到一个临时对象里面
      tmpMap[treeArray[i]["id"]] = treeArray[i];
    }
    for (i = 0, l = treeArray.length; i < l; i++) {
      var key = tmpMap[treeArray[i]["pid"]];
      console.log('key', key)
      //循环每一条数据的pid，假如这个临时对象有这个key值，就代表这个key对应的数据有children，需要Push进去
      //如果这一项数据属于哪个数据的子级
      if (key) {
        // 如果这个数据没有children
        if (!key["child"]) {
          key["child"] = [];
          key["child"].push(treeArray[i]);
          // 如果这个数据有children
        } else {
          key["child"].push(treeArray[i]);
        }
      } else {
        //如果没有这个Key值，就代表找不到属于哪个数据，那就代表没有父级,直接放在最外层
        r.push(treeArray[i]);
      }
    }
    return r
  }




  $scope.treeOptions = {
    nodeChildren: "child",
    dirSelectable: true,
    allowDeselect: false,
    injectClasses: {
      ul: "a1",
      li: "a2",
      liSelected: "a7",
      iExpanded: "a3",
      iCollapsed: "a4",
      iLeaf: "a5",
      label: "a6",
      labelSelected: "a8"
    }
  }




  $scope.searchDataChange = function (key_change) {
    console.log(key_change);
    // for (var key in $scope.searchData) {
    //   if (key != key_change) {
    //     $scope.searchData[key] = '*';
    //   } else {
    //     $scope.searchType = key;
    //   }
    // }
  }

  $scope.search = function (key_change) {

    $scope.SensorIDList = [];
    $scope.sensorsuccessList = [];
    $scope.sensorDangerList = [];

    $scope.postData = angular.copy($scope.searchData);


    if ($scope.searchType) {
      $scope.postType = $scope.searchType
    }
    console.log($scope.searchData);
    localStorage.setItem("sensorSearch", JSON.stringify($scope.searchData));

    $scope.getPage();
  }
});

var updateNode = null;
var updateProfile = null;
var nowGroup = null;

app.controller('quarantineCtrl', function ($scope, $http, $filter) {
  baseController($scope, $http, {
    getPage: "quarantine",
    update: "update"
  }, "quarantineNow");



});